package com.jinzhi.jzweb.service.impl;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.certificate.pojo.MyResultsVo;
import com.jinzhi.jzweb.dao.ExaminationResultsComDao;
import com.jinzhi.jzweb.domain.ExaminationResultsComDO;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.pojo.moduleConfig.*;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.PageLogicalUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 考试   成绩
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Service
public class ExaminationResultsComServiceImpl extends CoreServiceImpl<ExaminationResultsComDao, ExaminationResultsComDO> implements ExaminationResultsComService {

    @Autowired
    private CareStuSignUpComRealityService careStuSignUpComRealityService;

    @Override
    public Page<MyResultsVo> selByUserId(Map map,int current, int number) {

        // 新建分页
        Page<MyResultsVo> page = new Page<MyResultsVo>(current, number);

        return page.setRecords(this.baseMapper.selByUserId(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findLists(Map map,int current , int number) {
        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findLists(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findPageList(Map map, int current, int number) {

        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findPageList(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findList(Map map, int current, int number) {

        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findList(page,map));
    }

	@Override
	public List<ExaminationResultsExportVo> exportList(Map map) {
		
		return this.baseMapper.exportList(map);
	}

    @Override
    public List<ExaminationResultsExportAllVo> exportListAll(Map map) {
        return this.baseMapper.exportListAll(map);
    }

    @Override
    public List<ExaminationResultsPoVo> resultList(Long ebatchId) {
        return baseMapper.resultList(ebatchId);
    }

    @Override
    public List<ExaminationResultsABCPoVo> listABC() {
        return this.baseMapper.listABC();
    }


    /**
     * 制定照护计划分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> zhiDingStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Map map =new HashMap();
        map.put("field","A");
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        List<ExaminationResultsPoVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        double minValue = 0;//最小值
        double maxValue = 0;//最大值
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                //计算裁判平均分
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    //计算裁判打分平均分和最终得分
                    getAvgZhiDing(examinationResultsPoVo);
                }
                //考虑一名选手的情况
                if(valueList.size()==1){
                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    if(valueList.get(0).getDecrypt()==0){
                        examinationResultsPoVo.setDecrypt(0);
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    } else {
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,examinationResultsPoVo);
                        examinationResultsPoVo.setDecrypt(1);
                        examinationResultsPoVo.setRecordNumber(valueList.get(0).getRecordNumber());
                        valueList.add(examinationResultsPoVo);
                        //一人的分数即团队得分
                        double totalAverageScore = Double.parseDouble(valueList.get(0).getAverageScore());
                        valueList.get(0).setTotalAverageScore(String.valueOf(new BigDecimal(totalAverageScore).divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_HALF_UP)));
                        valueList.get(1).setTotalAverageScore(String.valueOf(new BigDecimal(totalAverageScore).divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_HALF_UP)));
                    }
                }
                //两名选手
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = (averageScore.add(averageScore2)).divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_HALF_UP);
                    valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                    valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));

                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    examinationResultsPoVo.setDecrypt(0);
                    //两个都未解密
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    }
                    //只有一个未解密
                    else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        valueList.get(0).setTotalAverageScore("******");
                        valueList.get(1).setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            valueList.remove(0);
                            valueList.add(examinationResultsPoVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            valueList.remove(1);
                            valueList.add(examinationResultsPoVo);
                        }
                    }
                }
                pageList.addAll(valueList);
            }

            //判断最高分和最低分是否隐藏
            boolean hasDecryptZero = pageList.stream()
                    .anyMatch(examinationResultsPoVo -> {
                        Integer decrypt = examinationResultsPoVo.getDecrypt();
                        return decrypt != null && decrypt == 0; // 先检查decrypt是否为null，再比较是否等于0
                    });
            if(hasDecryptZero){
                pageList.get(0).setMaxScore("******");
                pageList.get(0).setMinScore("******");
            }else{
                //获取最大值最小值
                // 获取最大值
                OptionalDouble maxScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
            }
        }
        List<ExaminationResultsPoVo> overallStatisticsVos = PageLogicalUtil.logicalPaginate(pageList, examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        if(null!=overallStatisticsVos && !overallStatisticsVos.isEmpty()){
            overallStatisticsVos.get(0).setMaxScore(String.valueOf(maxValue));
            overallStatisticsVos.get(0).setMinScore(String.valueOf(minValue));
            overallStatisticsVos.get(0).setPeopleNumber(pageList.size());
        }
        page.setTotal(pageList.size());
        page.setRecords(overallStatisticsVos);
        return page;
    }

    /**
     * 制定照护计划分数统计导出
     * @return
     */
    @Override
    public void zhiDingDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        Map map =new HashMap();
        map.put("field","A");
        List<ZhiDingScoreExcelVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                ZhiDingScoreExcelVo soreStatisticsVo = new ZhiDingScoreExcelVo();
                List<ZhiDingScoreChildrenExcelVo> childrenExcelList = new ArrayList<>();
                soreStatisticsVo.setUnitName(entry.getKey());//院校名称
                soreStatisticsVo.setRecordNumber(valueList.get(0).getRecordNumber());//检录号

                //计算裁判平均分
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    getAvgZhiDing(examinationResultsPoVo);
                    BeanUtils.copyProperties(examinationResultsPoVo,zhiDingScoreChildrenExcelVo);
                    childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                }
                //只存在一位选手的时候
                if(valueList.size()==1){
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    if(childrenExcelList.get(0).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                    }else {
                        //一位选手的得分及团队得分
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,zhiDingScoreChildrenExcelVo);
                        double totalAverageScore = Double.parseDouble(childrenExcelList.get(0).getAverageScore());//总成绩
                        soreStatisticsVo.setTotalAverageScore(String.valueOf(new BigDecimal(totalAverageScore).divide(new BigDecimal(2),2, BigDecimal.ROUND_HALF_UP)));
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                    }
                }
                //两位选手
                if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(childrenExcelList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(childrenExcelList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = (averageScore.add(averageScore2)).divide(new BigDecimal(2),2, BigDecimal.ROUND_HALF_UP);
                    soreStatisticsVo.setTotalAverageScore(String.valueOf(totalAverageScore));
                    //判断是否已经解密
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    zhiDingScoreChildrenExcelVo.setDecrypt(0);
                    if(childrenExcelList.get(0).getDecrypt()==0 && childrenExcelList.get(1).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        soreStatisticsVo = new ZhiDingScoreExcelVo();
                    } else if (childrenExcelList.get(0).getDecrypt()==0 || childrenExcelList.get(1).getDecrypt()==0) {
                        soreStatisticsVo.setTotalAverageScore("******");
                        if(childrenExcelList.get(0).getDecrypt()==0){
                            childrenExcelList.remove(0);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            childrenExcelList.remove(1);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        }
                    }
                }
                soreStatisticsVo.setScoreList(childrenExcelList);
                pageList.add(soreStatisticsVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(pageList, "制定照护计划分数导出", "制定照护计划分数导出", ZhiDingScoreExcelVo.class, "制定照护计划分数导出", response);
    }

    /**
     * 职业素养测评分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> zhiYeStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Map map =new HashMap();
        map.put("field","C");
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        List<ExaminationResultsPoVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        double minValue = 0;
        double maxValue = 0;
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                //考虑一名选手的情况
                if(valueList.size()==1){
                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    if(valueList.get(0).getDecrypt()==0){
                        examinationResultsPoVo.setDecrypt(0);
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    } else {
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,examinationResultsPoVo);
                        examinationResultsPoVo.setDecrypt(1);
                        examinationResultsPoVo.setRecordNumber(valueList.get(0).getRecordNumber());
                        valueList.add(examinationResultsPoVo);
                        //一人的分数即团队得分
                        double totalAverageScore = Double.parseDouble(valueList.get(0).getAverageScore());
                        valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore/2));
                        valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore/2));
                    }
                }
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = (averageScore.add(averageScore2)).divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_HALF_UP);
                    valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                    valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));

                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    examinationResultsPoVo.setDecrypt(0);
                    //两个都未解密
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    }
                    //一个已经解密
                    else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        valueList.get(0).setTotalAverageScore("******");
                        valueList.get(1).setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            valueList.remove(0);
                            valueList.add(examinationResultsPoVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            valueList.remove(1);
                            valueList.add(examinationResultsPoVo);
                        }
                    }
                }
                pageList.addAll(valueList);
            }

            //判断最高分和最低分是否隐藏
            boolean hasDecryptZero = pageList.stream()
                    .anyMatch(examinationResultsPoVo -> {
                        Integer decrypt = examinationResultsPoVo.getDecrypt();
                        return decrypt != null && decrypt == 0; // 先检查decrypt是否为null，再比较是否等于0
                    });
            if(hasDecryptZero){
                pageList.get(0).setMaxScore("******");
                pageList.get(0).setMinScore("******");
            }else{
                //获取最大值最小值
                // 获取最大值
                OptionalDouble maxScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
            }
        }
        //逻辑分页
        List<ExaminationResultsPoVo> overallStatisticsVos = PageLogicalUtil.logicalPaginate(pageList, examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        if(null!=overallStatisticsVos && !overallStatisticsVos.isEmpty()){
            overallStatisticsVos.get(0).setMaxScore(String.valueOf(maxValue));
            overallStatisticsVos.get(0).setMinScore(String.valueOf(minValue));
            overallStatisticsVos.get(0).setPeopleNumber(pageList.size());
        }
        page.setTotal(pageList.size());
        page.setRecords(overallStatisticsVos);
        return page;
    }

    /**
     * 职业素养测评分数导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void zhiYeDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        Map map =new HashMap();
        map.put("field","C");
        List<ZhiYeScoreExcelVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                ZhiYeScoreExcelVo zhiDingScoreExcelVo = new ZhiYeScoreExcelVo();
                List<ZhiYeScoreChildrenExcelVo> childrenExcelList = new ArrayList<>();
                zhiDingScoreExcelVo.setUnitName(entry.getKey());//院校名称
                zhiDingScoreExcelVo.setRecordNumber(valueList.get(0).getRecordNumber());//检录号
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    ZhiYeScoreChildrenExcelVo zhiYeScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    BeanUtils.copyProperties(examinationResultsPoVo,zhiYeScoreChildrenExcelVo);
                    childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                }
                //一位选手的情况
                if(valueList.size()==1){
                    ZhiYeScoreChildrenExcelVo zhiYeScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    if(childrenExcelList.get(0).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                    }else {
                        //一位选手的得分及团队得分
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,zhiYeScoreChildrenExcelVo);
                        zhiDingScoreExcelVo.setTotalAverageScore(String.valueOf(new BigDecimal(valueList.get(0).getAverageScore()).divide(new BigDecimal(2))));//总成绩
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                    }

                }
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = (averageScore.add(averageScore2)).divide(new BigDecimal(2)).setScale(2,BigDecimal.ROUND_HALF_UP);
                    zhiDingScoreExcelVo.setTotalAverageScore(String.valueOf(totalAverageScore));
                    //判断是否已经解密
                    ZhiYeScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    zhiDingScoreChildrenExcelVo.setDecrypt(0);
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        zhiDingScoreExcelVo = new ZhiYeScoreExcelVo();
                    } else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        zhiDingScoreExcelVo.setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            childrenExcelList.remove(0);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            childrenExcelList.remove(1);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        }
                    }
                }
                zhiDingScoreExcelVo.setScoreList(childrenExcelList);
                pageList.add(zhiDingScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(pageList, "职业素养测评分数导出", "职业素养测评分数导出", ZhiYeScoreExcelVo.class, "职业素养测评分数导出", response);
    }

    /**
     * 实操居家场景分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> juJiaStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        Map map =new HashMap();
        map.put("field","B1");
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        boolean flag = false;//用来判断是否显示最高分最低分
        double minValue = 0;//最小值
        double maxValue = 0;//最大值
        if (examinationResultsPoVos!=null && !examinationResultsPoVos.isEmpty()) {
            int i=0;
            for (ExaminationResultsPoVo examinationResultsPoVo : examinationResultsPoVos) {
                if(examinationResultsPoVo.getDecrypt()==0){
                    examinationResultsPoVos.set(i, new ExaminationResultsPoVo()); // 将满足条件的元素设置为null
                    flag = true;
                }else{
                    //计算裁判打分平均分和最终得分
                    getAvgJuJia(examinationResultsPoVo);
                }
                i+=1;
            }
            if(flag){
                examinationResultsPoVos.get(0).setMaxScore("******");
                examinationResultsPoVos.get(0).setMinScore("******");
            }else{
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
            }
        }
        //逻辑分页
        List<ExaminationResultsPoVo> overallStatisticsVos = PageLogicalUtil.logicalPaginate(examinationResultsPoVos, examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        if(null!=overallStatisticsVos && !overallStatisticsVos.isEmpty()){
            overallStatisticsVos.get(0).setMaxScore(String.valueOf(maxValue));
            overallStatisticsVos.get(0).setMinScore(String.valueOf(minValue));
            overallStatisticsVos.get(0).setPeopleNumber(examinationResultsPoVos.size());
        }

        page.setRecords(overallStatisticsVos);
        page.setTotal(examinationResultsPoVos.size());
        return page;
    }


    /**
     * 实操居家场景分数统计导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void juJiaDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        examinationAnswerSheetComDT.setPageNumber(1);
        examinationAnswerSheetComDT.setPageSize(9999);
        List<ExaminationResultsPoVo> records = this.juJiaStatistics(examinationAnswerSheetComDT).getRecords();
        List<JuJiaScoreExcelVo> juJiaScoreExcelVoList = new ArrayList<>();
        if (records!=null && !records.isEmpty()) {
            for (ExaminationResultsPoVo record : records) {
                JuJiaScoreExcelVo juJiaScoreExcelVo = new JuJiaScoreExcelVo();
                BeanUtils.copyProperties(record,juJiaScoreExcelVo);
                juJiaScoreExcelVoList.add(juJiaScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(juJiaScoreExcelVoList, "实操居家场景分数统计导出", "实操居家场景分数统计导出", JuJiaScoreExcelVo.class, "实操居家场景分数统计导出", response);
    }

    /**
     * 月子中心场景成绩统计
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> yueZiStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        Map map =new HashMap();
        map.put("field","B2");
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        boolean flag = false;//用来判断是否显示最高分最低分
        double minValue = 0;//最小值
        double maxValue = 0;//最大值
        if (examinationResultsPoVos!=null && !examinationResultsPoVos.isEmpty()) {
            int i=0;
            for (ExaminationResultsPoVo examinationResultsPoVo : examinationResultsPoVos) {
                if(examinationResultsPoVo.getDecrypt()==0){
                    examinationResultsPoVos.set(i, new ExaminationResultsPoVo()); // 将满足条件的元素设置为null
                    flag = true;
                }else{
                    //计算裁判打分平均分和最终得分
                    getAvgJuJia(examinationResultsPoVo);
                }
                i+=1;
            }
            if(flag){
                examinationResultsPoVos.get(0).setMaxScore("******");
                examinationResultsPoVos.get(0).setMinScore("******");
            }else{
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
            }
        }
        //逻辑分页
        List<ExaminationResultsPoVo> overallStatisticsVos = PageLogicalUtil.logicalPaginate(examinationResultsPoVos, examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        if(null!=overallStatisticsVos && !overallStatisticsVos.isEmpty()){
            overallStatisticsVos.get(0).setMaxScore(String.valueOf(maxValue));
            overallStatisticsVos.get(0).setMinScore(String.valueOf(minValue));
            overallStatisticsVos.get(0).setPeopleNumber(examinationResultsPoVos.size());
        }

        page.setRecords(examinationResultsPoVos);
        page.setTotal(examinationResultsPoVos.size());
        return page;
    }

    /**
     * 月子中心场景分数统计导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void yueZiDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        examinationAnswerSheetComDT.setPageNumber(1);
        examinationAnswerSheetComDT.setPageSize(9999);
        List<ExaminationResultsPoVo> records = this.yueZiStatistics(examinationAnswerSheetComDT).getRecords();
        List<JuJiaScoreExcelVo> juJiaScoreExcelVoList = new ArrayList<>();
        if (records!=null && !records.isEmpty()) {
            for (ExaminationResultsPoVo record : records) {
                JuJiaScoreExcelVo juJiaScoreExcelVo = new JuJiaScoreExcelVo();
                BeanUtils.copyProperties(record,juJiaScoreExcelVo);
                juJiaScoreExcelVoList.add(juJiaScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(juJiaScoreExcelVoList, "月子中心场景分数统计导出", "月子中心场景分数统计导出", JuJiaScoreExcelVo.class, "月子中心场景分数统计导出", response);
    }

    /**
     * 成绩总统计
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public Page<OverallStatisticsVo> overallStatistics(ExaminationResultsComDO examinationResultsComDO) {
        //判断是都已经全部解密
        boolean flag = false;
        LinkedHashMap<String,OverallStatisticsVo> map = new LinkedHashMap<>();
        //查询学校信息
        List<CareStuSignUpComRealityDO> unitNameList = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().groupBy("unit_name").orderBy("record_sort",true));
        for (CareStuSignUpComRealityDO careStuSignUpComRealityDO : unitNameList) {
            if(careStuSignUpComRealityDO.getDecryptAll()==0){
                flag = true;
            }
            OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
            BeanUtils.copyProperties(careStuSignUpComRealityDO,overallStatisticsVo);
            map.put(careStuSignUpComRealityDO.getUnitName(),overallStatisticsVo);
        }

        List<ExaminationResultsPoVo> listA = new ArrayList<>();
        List<ExaminationResultsPoVo> listB1 = new ArrayList<>();
        List<ExaminationResultsPoVo> listB2 = new ArrayList<>();
        List<ExaminationResultsPoVo> listC = new ArrayList<>();
        //查询A赛场制定照护计划成绩
        Map mapA =new HashMap();
        List<ExaminationResultsPoVo> listAll = this.baseMapper.listScore(mapA);
        if(null!=listAll && !listAll.isEmpty()){
            listAll.forEach(a->{
                switch (a.getField()){
                    case "A":listA.add(a);break;
                    case "B1":listB1.add(a);break;
                    case "B2":listB2.add(a);break;
                    case "C":listC.add(a);break;
                }
            });
        }


        //制定照护计划
        if(listA!=null && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                String name = examinationResultsPoVo.getName();
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();
                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgZhiDing(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = map.get(unitName);
                //选手一
                if(null==overallStatisticsVo.getNameA1() || overallStatisticsVo.getNameA1().equals("-")){
                    BeanUtils.copyProperties(examinationResultsPoVo,overallStatisticsVo);
                    overallStatisticsVo.setNameA1(name);//参赛选手
                    overallStatisticsVo.setNum1A1(num1);//一次加密
                    overallStatisticsVo.setNum2A1(num2);//二次加密
                    overallStatisticsVo.setScoreA1(examinationResultsPoVo.getJudgment());//裁判每项打分
                    overallStatisticsVo.setAvg1(Double.parseDouble(examinationResultsPoVo.getAverageScore()));//裁判打分平均分
                    map.replace(unitName,overallStatisticsVo);
                }
                else{
                    //选手二
                    overallStatisticsVo.setNameA2(name);//参赛选手
                    overallStatisticsVo.setNum1A2(num1);//一次加密
                    overallStatisticsVo.setNum2A2(num2);//二次加密
                    overallStatisticsVo.setScoreA2(examinationResultsPoVo.getJudgment());//裁判每项打分
                    overallStatisticsVo.setAvg2(Double.parseDouble(examinationResultsPoVo.getAverageScore()));//裁判打分平均分
                    BigDecimal avg1 = new BigDecimal(overallStatisticsVo.getAvg1());
                    BigDecimal avg2 = new BigDecimal(overallStatisticsVo.getAvg2());
                    overallStatisticsVo.setTotalScoreA(String.valueOf((avg1.add(avg2)).divide(new BigDecimal(2)).setScale(2, BigDecimal.ROUND_HALF_UP)));//制定照护计划最终得分
                    map.replace(examinationResultsPoVo.getUnitName(),overallStatisticsVo);
                }
            }
        }
        //居家场景
        if(listB1!=null && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();

                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgJuJia(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                overallStatisticsVo.setRecordNumber(examinationResultsPoVo.getRecordNumber());
                overallStatisticsVo.setUnitName(unitName);
                overallStatisticsVo.setDecrypt(examinationResultsPoVo.getDecrypt());
                overallStatisticsVo.setNum1B1(num1);//一次加密
                overallStatisticsVo.setNum2B1(num2);//二次加密
                overallStatisticsVo.setScoreB1One(examinationResultsPoVo.getJudgment());//居家场景婴幼儿照护打分
                overallStatisticsVo.setScoreB1Two(examinationResultsPoVo.getJudgment2());//居家场景产妇照护打分打分
                overallStatisticsVo.setTotalScoreB1(examinationResultsPoVo.getTotalAverageScore());//裁判打分平均分

                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else {
                    map.put(unitName,overallStatisticsVo);
                }
            }
        }
        //月子场景
        if(listB2!=null && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();

                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgJuJia(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                overallStatisticsVo.setRecordNumber(examinationResultsPoVo.getRecordNumber());
                overallStatisticsVo.setUnitName(unitName);
                overallStatisticsVo.setDecrypt(examinationResultsPoVo.getDecrypt());
                overallStatisticsVo.setNum1B2(num1);//一次加密
                overallStatisticsVo.setNum2B2(num2);//二次加密
                overallStatisticsVo.setScoreB2One(examinationResultsPoVo.getJudgment());//居家场景婴幼儿照护打分
                overallStatisticsVo.setScoreB2Two(examinationResultsPoVo.getJudgment2());//居家场景产妇照护打分打分
                overallStatisticsVo.setTotalScoreB2(examinationResultsPoVo.getTotalAverageScore());//裁判打分平均分
                map.replace(unitName,overallStatisticsVo);
                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else{
                    map.put(unitName,overallStatisticsVo);
                }

            }
        }
        //职业素养测评
        if(listC!=null && !listC.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = listC.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){

                String unitName = entry.getKey();

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                List<ExaminationResultsPoVo> valueList = entry.getValue();

                //计算团队得分
                if(valueList.size()==2){
                    overallStatisticsVo.setNameC1(valueList.get(0).getName());//选手姓名
                    overallStatisticsVo.setNum1C1(valueList.get(0).getNum1());//一次加密
                    overallStatisticsVo.setNum2C1(valueList.get(0).getNum2());//二次加密
                    overallStatisticsVo.setScoreC1(valueList.get(0).getAverageScore());//素养测评考试得分
                    overallStatisticsVo.setTotalScoreC(String.valueOf(new BigDecimal(valueList.get(0).getAverageScore()).divide(new BigDecimal(2))));//C赛场总得分

                    overallStatisticsVo.setNameC2(valueList.get(1).getName());
                    overallStatisticsVo.setNum1C2(valueList.get(1).getNum1());
                    overallStatisticsVo.setNum2C2(valueList.get(1).getNum2());
                    overallStatisticsVo.setScoreC2(valueList.get(1).getAverageScore());
                    BigDecimal scoreC1 = new BigDecimal(overallStatisticsVo.getScoreC1());
                    BigDecimal scoreC2 = new BigDecimal(overallStatisticsVo.getScoreC2());
                    overallStatisticsVo.setTotalScoreC(String.valueOf((scoreC1.add(scoreC2)).divide(new BigDecimal(2))));
                }
                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else{
                    map.put(unitName,overallStatisticsVo);
                }
            }
        }
        Page<OverallStatisticsVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页

        List<OverallStatisticsVo> list = new ArrayList<>();
        double minValue = 0;//最低分
        double maxValue = 0;//最高分
        if(!map.isEmpty()){
            for (Map.Entry<String, OverallStatisticsVo> entry : map.entrySet()){
                OverallStatisticsVo value = entry.getValue();
                BigDecimal totalScoreA = new BigDecimal(0);
                BigDecimal totalScoreB1 = new BigDecimal(0);
                BigDecimal totalScoreB2 = new BigDecimal(0);
                BigDecimal totalScoreC = new BigDecimal(0);
                BigDecimal totalAverageScore = new BigDecimal(0);
                //计算总分
                if(!value.getTotalScoreA().equals("-")){
                    totalScoreA = new BigDecimal(value.getTotalScoreA());
                }
                if(!value.getTotalScoreB1().equals("-")){
                    totalScoreB1 = new BigDecimal(value.getTotalScoreB1());
                }
                if(!value.getTotalScoreB2().equals("-")){
                    totalScoreB2 = new BigDecimal(value.getTotalScoreB2());
                }
                if(!value.getTotalScoreC().equals("-")){
                    totalScoreC = new BigDecimal(value.getTotalScoreC());
                }
                totalAverageScore = totalScoreA.add(totalScoreB1).add(totalScoreB2).add(totalScoreC).setScale(2,BigDecimal.ROUND_HALF_UP);;
                value.setTotalAverageScore(String.valueOf(totalAverageScore));
                list.add(value);
            }
            if(flag){
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                    OverallStatisticsCopyVo overallStatisticsCopyVo = new OverallStatisticsCopyVo();
                    BeanUtils.copyProperties(overallStatisticsCopyVo,overallStatisticsVo);
                    list.set(i,overallStatisticsVo);
                }
            }else {
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = list.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = list.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
            }
        }
        //逻辑分页
        List<OverallStatisticsVo> overallStatisticsVos = PageLogicalUtil.logicalPaginate(list, examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());
        if(null!=overallStatisticsVos && !overallStatisticsVos.isEmpty()){
            overallStatisticsVos.get(0).setMaxScore(String.valueOf(maxValue));
            overallStatisticsVos.get(0).setMinScore(String.valueOf(minValue));
            overallStatisticsVos.get(0).setPeopleNumber(list.size() * 2);
        }
        page.setTotal(list.size());
        page.setRecords(overallStatisticsVos);

        return page;
    }

    /**
     * 获取制定照护计划裁判打分平均分
     * @param examinationResultsPoVo
     */
    public void getAvgZhiDing(ExaminationResultsPoVo examinationResultsPoVo){
        double all = 0.0;
        BigDecimal avg = new BigDecimal(0);
        String judgment = "-";//裁判打分 例：50/50/50
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4())
                    + Double.valueOf(examinationResultsPoVo.getScore5());
            avg = new BigDecimal(all).divide(new BigDecimal(5), 2, BigDecimal.ROUND_HALF_UP);
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3() +"/"+ examinationResultsPoVo.getScore4() +"/"+ examinationResultsPoVo.getScore5();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4());
            avg = new BigDecimal(all).divide(new BigDecimal(4), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5("-");
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3() +"/"+ examinationResultsPoVo.getScore4();
        }
        //三位
        else {
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3());
            avg = new BigDecimal(all).divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5("-");
            examinationResultsPoVo.setScore4("-");
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3();
        }
        examinationResultsPoVo.setAverageScore(String.valueOf(avg));
        examinationResultsPoVo.setJudgment(judgment);
    }

    /**
     * 获取居家场景裁判打分平均分
     * @param examinationResultsPoVo
     */
    public void getAvgJuJia(ExaminationResultsPoVo examinationResultsPoVo){
        double all = 0.0;//婴幼儿照护总分
        BigDecimal avg = new BigDecimal(0);//婴幼儿照护平均分
        String judgment = "";//裁判打分
        //计算最终得分
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4())
                    + Double.valueOf(examinationResultsPoVo.getScore5());
            avg = new BigDecimal(all).divide(new BigDecimal(5), 2, BigDecimal.ROUND_HALF_UP);
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3() + "/" + examinationResultsPoVo.getScore4() + "/" + examinationResultsPoVo.getScore5();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4());
            avg = new BigDecimal(all).divide(new BigDecimal(4), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5("-");
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3() + "/" + examinationResultsPoVo.getScore4();
        }
        //三位
        else {
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3());
            avg = new BigDecimal(all).divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5("-");
            examinationResultsPoVo.setScore4("-");
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3();
        }

        double allS = 0.0;//产妇照护总分
        BigDecimal avgS =new BigDecimal(0);//产妇照护总分
        String judgment1 = "";//裁判打分
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5s())!=-1){
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s()) + Double.valueOf(examinationResultsPoVo.getScore4s())
                    + Double.valueOf(examinationResultsPoVo.getScore5s());
            avgS = new BigDecimal(allS).divide(new BigDecimal(5), 2, BigDecimal.ROUND_HALF_UP);
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s() + "/" + examinationResultsPoVo.getScore4s() + "/" + examinationResultsPoVo.getScore5s();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4s())!=-1){
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s()) + Double.valueOf(examinationResultsPoVo.getScore4s());
            avgS = new BigDecimal(allS).divide(new BigDecimal(4), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5s("-");
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s() + "/" + examinationResultsPoVo.getScore4s();
        }
        //三位
        else {
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s());
            avgS = new BigDecimal(allS).divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP);
            examinationResultsPoVo.setScore5s("-");
            examinationResultsPoVo.setScore4s("-");
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s();
        }
        examinationResultsPoVo.setTotalAverageScore(String.valueOf(avg.add(avgS).setScale(2, RoundingMode.HALF_UP)));//选手最终得分
        examinationResultsPoVo.setAverageScore1(avg.doubleValue());
        examinationResultsPoVo.setAverageScore2(avgS.doubleValue());
        examinationResultsPoVo.setJudgment(judgment);
        examinationResultsPoVo.setJudgment2(judgment1);
    }

    /**
     * 成绩总统计导出
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public void overallStatisticsDownloadImport(HttpServletResponse response,ExaminationResultsComDO examinationResultsComDO) {
        examinationResultsComDO.setPageSize(999);
        examinationResultsComDO.setPageNumber(1);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();

        //导出操作
        EasyPoiUtil.exportExcel(records, "成绩总统计导出", "成绩总统计导出", OverallStatisticsVo.class, "成绩总统计导出", response);
    }

    /**
     * 成绩公式表导出
     * @param response
     * @param examinationResultsComDO
     */
    @Override
    public void documentWord(HttpServletResponse response, ExaminationResultsComDO examinationResultsComDO) throws Exception {
        examinationResultsComDO.setPageSize(999);
        examinationResultsComDO.setPageNumber(1);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();

        //导出组装数据
        Map<String,Object> params =new HashMap<>();
        //暂定
        params.put("batchName","全国职业院校技能大赛-母婴照护赛项");
        List<OverallStatisticsVo> listStu = new ArrayList<>();
        if(records!=null && !records.isEmpty()){
            listStu = records.stream()
                    .filter(vo -> !"-".equals(vo.getTotalAverageScore()) && !"******".equals(vo.getTotalAverageScore()))
                    .sorted((vo1, vo2) -> {
                        try {
                            double score1 = Double.parseDouble(vo1.getTotalAverageScore());
                            double score2 = Double.parseDouble(vo2.getTotalAverageScore());
                            return Double.compare(score2, score1); // 降序排序
                        } catch (NumberFormatException e) {
                            // 处理无法解析的情况，可以决定它们的相对顺序
                            // 这里假设无法解析的字符串应被视为最低分数
                            return 1; // vo1 排在 vo2 后面，实现降序效果
                        }
                    })
                    .collect(Collectors.toList());
            for (int i = 1; i <= listStu.size(); i++) {
                listStu.get(i-1).setSort(i);
            }
        }


        params.put("listStu",listStu);

        XWPFDocument word = WordExportUtil.exportWord07(templateFile().getPath(),params);
        response.setHeader("content-disposition","attachment;filename="+new String("成绩公示表.docx".getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        word.write(response.getOutputStream());
    }

    //获取docx文件位置
    private File templateFile() throws IOException {

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("scoreTemplate.docx");
        if (inputStream == null) {
            throw new RuntimeException("Template file not found in resources");
        }

        // 将输入流转换为临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("template", ".docx");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        tempFile.deleteOnExit(); // 在JVM退出时删除临时文件
        Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return tempFile;
    }

    /**
     * 各模块得分统计数据
     */
    @Override
    public Result<?> moduleScoreList() {
        ExaminationCostStatisticModuleScoreVo resultVO = new ExaminationCostStatisticModuleScoreVo();
        List<Double> fullList = new ArrayList<>();/** 满分 */
        fullList.add(10.0);
        fullList.add(20.0);
        fullList.add(15.0);
        fullList.add(20.0);
        fullList.add(15.0);
        fullList.add(20.0);
        List<Double> nationList = new ArrayList<>();/** 各模块得分*/
        List<Double> highestList = new ArrayList<>();/** 最高分 */
        List<Double> lowestList = new ArrayList<>();/** 最低分 */
        List<Double> averageList = new ArrayList<>();/** 平均分 */
        List<Double> poorList = new ArrayList<>();/** 分差 */

        //查询制定照护计划裁判打分
        Map mapA =new HashMap();
        mapA.put("field","A");
        List<ExaminationResultsPoVo> listA = this.baseMapper.listScoreByField(mapA);
        if(null!=listA && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                getAvgZhiDing(examinationResultsPoVo);
            }
            getScoreNums(highestList, lowestList, averageList, poorList, listA);
        }else{
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询B赛场居家场景成绩
        Map mapB1 =new HashMap();
        mapB1.put("field","B1");
        List<ExaminationResultsPoVo> listB1 = this.baseMapper.listScoreByField(mapB1);
        if(listB1!=null && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                getAvgJuJia(examinationResultsPoVo);
            }
            //计算婴幼儿照护分数（最高、最低、平均、分差）
            getScoreNums2(highestList, lowestList, averageList, poorList, listB1);
        }else {
            addList(highestList,lowestList,averageList,poorList);
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询B赛场月子场景成绩
        Map mapB2 =new HashMap();
        mapB2.put("field","B2");
        List<ExaminationResultsPoVo> listB2 = this.baseMapper.listScoreByField(mapB2);
        if(listB2!=null && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                getAvgJuJia(examinationResultsPoVo);
            }
            //计算婴幼儿照护分数（最高、最低、平均、分差）
            getScoreNums2(highestList, lowestList, averageList, poorList, listB2);
        }else{
            addList(highestList,lowestList,averageList,poorList);
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询C赛场职业素养测评成绩
        Map mapC =new HashMap();
        mapC.put("field","C");
        List<ExaminationResultsPoVo> listC = this.baseMapper.listScoreByField(mapC);
        if(listC!=null && !listC.isEmpty()){
            //计算（最高、最低、平均、分差）
            getScoreNums(highestList, lowestList, averageList, poorList, listC);
        }else {
            addList(highestList,lowestList,averageList,poorList);
        }


        resultVO.setNationList(nationList);
        resultVO.setFullList(fullList);
        resultVO.setHighestList(highestList);
        resultVO.setLowestList(lowestList);
        resultVO.setAverageList(averageList);
        resultVO.setPoorList(poorList);
        return Result.ok(resultVO);
    }

    //获取实操最高、最低、平均、分差
    private void getScoreNums(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, List<ExaminationResultsPoVo> listA) {
        double maxScore = Double.parseDouble(Collections.max(listA, Comparator.comparingDouble(poVo->Double.parseDouble(poVo.getAverageScore()))).getAverageScore());
        double minScore = Double.parseDouble(Collections.min(listA, Comparator.comparingDouble(poVo->Double.parseDouble(poVo.getAverageScore()))).getAverageScore());
        double averageScore = Math.round((listA.stream().mapToDouble(poVo->Double.parseDouble(poVo.getAverageScore())).average().orElse(0))* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore, minScore, averageScore);
    }

    //计算分差
    private void getScorePoor(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, double maxScore, double minScore, double averageScore) {
        // 防止精度丢失 将double转换为String，然后再创建BigDecimal对象
        BigDecimal maxDecimal = new BigDecimal(Double.toString(maxScore));
        BigDecimal minDecimal = new BigDecimal(Double.toString(minScore));
        double poor = maxDecimal.subtract(minDecimal).doubleValue();
        highestList.add(maxScore);
        lowestList.add(minScore);
        averageList.add(averageScore);
        poorList.add(poor);
    }

    //获取职业素养测评和制定照护计划最高、最低、平均、分差
    private void getScoreNums2(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, List<ExaminationResultsPoVo> list) {
        //计算婴幼儿照护分数（最高、最低、平均、分差）
        double maxScore = Collections.max(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore1)).getAverageScore1();
        double minScore = Collections.min(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore1)).getAverageScore1();
        double averageScore = Math.round(list.stream().mapToDouble(ExaminationResultsPoVo::getAverageScore1).average().orElse(0)* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore, minScore, averageScore);
        //计算产妇照护分数（最高、最低、平均、分差）
        double maxScore2 = Collections.max(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore2)).getAverageScore2();
        double minScore2 = Collections.min(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore2)).getAverageScore2();
        double averageScore2 = Math.round(list.stream().mapToDouble(ExaminationResultsPoVo::getAverageScore2).average().orElse(0)* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore2, minScore2, averageScore2);
    }

    public void addList(List<Double> highestList,List<Double> lowestList,List<Double> averageList,List<Double> poorList){
        highestList.add(0.0);
        lowestList.add(0.0);
        averageList.add(0.0);
        poorList.add(0.0);
    }


    /**
     * 总得分占比
     * @return
     */
    @Override
    public Result<?> totalScoreList() {
        ExaminationCostStatisticTotalScoreVo resultVO = new ExaminationCostStatisticTotalScoreVo();
        List<String> totalScoreList = new ArrayList<>(); /** 总得分占比折线图 */
        List<NationVo> totalScorePercentage = new ArrayList<>(); /** 总得分占比 饼图 */
        List<Double> scoreList = new ArrayList<>();
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        examinationResultsComDO.setPageNumber(1);
        examinationResultsComDO.setPageSize(999);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();
        if(null!=records && !records.isEmpty()){
            for (OverallStatisticsVo record : records) {
                if(record.getTotalAverageScore()!=null && !record.getTotalAverageScore().equals("-") && !record.getTotalScoreA().equals("******")){
                    scoreList.add(Double.valueOf(record.getTotalAverageScore()));
                }
            }
        }
        Integer i20 = 0;
        Integer i40 = 0;
        Integer i60 = 0;
        Integer i80 = 0;
        Integer i90 = 0;
        Integer i100 = 0;
        if(!scoreList.isEmpty()){
            for (Double s : scoreList) {
                if(s<=20.0){
                    i20+=1;
                } else if (s<=40.0) {
                    i40+=1;
                } else if (s<=60.0) {
                    i60+=1;
                } else if (s<=80.0) {
                    i80+=1;
                } else if (s<=90.0) {
                    i80+=1;
                } else if (s<=100.0) {
                    i100+=1;
                }
            }
        }
        Integer total = i20 + i40 + i60 + i80 + i90 + i100;
        //计算总得分占比
        if(total!=0){
            NationVo nation20 = new NationVo();
            NationVo nation40 = new NationVo();
            NationVo nation60 = new NationVo();
            NationVo nation80 = new NationVo();
            NationVo nation90 = new NationVo();
            NationVo nation100 = new NationVo();
            nation20.setName("0 - 20分");
            nation40.setName("21 - 40分");
            nation60.setName("41 - 60分");
            nation80.setName("61 - 80分");
            nation90.setName("81 - 90分");
            nation100.setName("91 - 100分");
            getTotalScoreList(nation20,i20,total,totalScoreList);
            getTotalScoreList(nation40,i40,total,totalScoreList);
            getTotalScoreList(nation60,i60,total,totalScoreList);
            getTotalScoreList(nation80,i80,total,totalScoreList);
            getTotalScoreList(nation90,i90,total,totalScoreList);
            getTotalScoreList(nation100,i100,total,totalScoreList);

            totalScorePercentage.add(nation20);
            totalScorePercentage.add(nation40);
            totalScorePercentage.add(nation60);
            totalScorePercentage.add(nation80);
            totalScorePercentage.add(nation90);
            totalScorePercentage.add(nation100);

        }

        resultVO.setTotalScoreList(totalScoreList);
        resultVO.setTotalScorePercentage(totalScorePercentage);

        return Result.ok(resultVO);
    }

    /**
     *
     * @param nationVo 分数饼图信息
     * @param nationI 每个区间的分数数量
     * @param total 总分数
     * @param totalScoreList 分数占比折线图
     */
    public void getTotalScoreList(NationVo nationVo,Integer nationI,Integer total,List<String> totalScoreList){
        if(nationI==0){
            totalScoreList.add("0");
            nationVo.setValue("0");
        }else {
            BigDecimal bigDecimal = new BigDecimal(nationI).divide(new BigDecimal(total), 2, BigDecimal.ROUND_HALF_UP) // 指定舍入模式和精度
                    .multiply(new BigDecimal("100"));
            totalScoreList.add(String.valueOf(bigDecimal));
            nationVo.setValue(String.valueOf(bigDecimal));
        }
    }

    public void getScoreRange(double score,int[] nums){
        if(score<=60){
            nums[0]+=1;
        }else if (score<=70) {
            nums[1]+=1;
        } else if (score<=80) {
            nums[2]+=1;
        } else if (score<=90) {
            nums[3]+=1;
        } else if (score<=100) {
            nums[4]+=1;
        }
    }

    public void addScoreRange(List<Integer> list,int[] nums){
        list.add(nums[0]);
        list.add(nums[1]);
        list.add(nums[2]);
        list.add(nums[3]);
        list.add(nums[4]);
    }

    public int[] createNums(){
        int[] nums = new int[5];
        nums[0] = 0;
        nums[1] = 0;
        nums[2] = 0;
        nums[3] = 0;
        nums[4] = 0;

        return nums;
    }

    /**
     * 百分制分值
     * 制定照护计划满分10分  百分制：10*10
     * 居家场景满分35分     百分制：35*2.85
     * 月子中心场景满分35分  百分制：35*2.85
     * 职业素养测评满分20分  百分制：20*5
     * @return
     */
    @Override
    public Result<?> scoreRangeList() {
        ExaminationCostStatisticScoreRangeVo resultVO = new ExaminationCostStatisticScoreRangeVo();
        DecimalFormat df = new DecimalFormat("#.00");
        List<Integer> zhiDingList = new ArrayList<>();/** 制定照护计划折线图 */
        List<Integer> juJiaList = new ArrayList<>();;/** 居家场景折线图 */
        List<Integer> yueZiList = new ArrayList<>();;/** 月子场景折线图 */
        List<Integer> zhiYeList = new ArrayList<>();;/** 职业素养测评折线图 */
        //查询制定照护计划裁判打分
        Map mapA =new HashMap();
        mapA.put("field","A");
        List<ExaminationResultsPoVo> listA = this.baseMapper.listScoreByField(mapA);
        int[] numsA = createNums();
        if(null!=listA && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                getAvgZhiDing(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getAverageScore());
                double v = averageScore * 10;
                getScoreRange(v,numsA);
            }
        }
        addScoreRange(zhiDingList,numsA);

        //查询居家场景裁判打分裁判打分
        Map mapB1 =new HashMap();
        mapB1.put("field","B1");
        List<ExaminationResultsPoVo> listB1 = this.baseMapper.listScoreByField(mapB1);
        int[] numsB1  = createNums();
        if(null!=listB1 && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                getAvgJuJia(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getTotalAverageScore());
                double v = averageScore * 2.85;
                getScoreRange(v,numsB1);
            }
        }
        addScoreRange(juJiaList,numsB1);

        //查询月子场景裁判打分裁判打分
        Map mapB2 =new HashMap();
        mapB2.put("field","B2");
        List<ExaminationResultsPoVo> listB2 = this.baseMapper.listScoreByField(mapB2);
        int[] numsB2 = createNums();
        if(null!=listB2 && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                getAvgJuJia(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getTotalAverageScore());
                double v = averageScore * 2.85;
                getScoreRange(v,numsB2);
            }
        }
        addScoreRange(yueZiList,numsB2);


        //查询职业素养测评分数
        Map mapC =new HashMap();
        mapC.put("field","C");
        List<ExaminationResultsPoVo> listC = this.baseMapper.listScoreByField(mapC);
        int[] numsC = createNums();
        if(null!=listC && !listC.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                double v = Double.valueOf(examinationResultsPoVo.getAverageScore()) * 5;
                getScoreRange(v,numsC);
            }
        }
        addScoreRange(zhiYeList,numsC);

        resultVO.setZhiYeList(zhiYeList);
        resultVO.setJuJiaList(juJiaList);
        resultVO.setYueZiList(yueZiList);
        resultVO.setZhiDingList(zhiDingList);
        return Result.ok(resultVO);
    }

}
